<template>
  <el-container>
    <el-header height="40px">
      <el-form :inline="true">
        <el-form-item label="用户名字">
          <el-input
            suffix-icon="el-icon-search"
            placeholder="请输入搜索的用户名"
            v-model="search.user_name"
            @input="getUsers(true)"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="用户角色">
          <el-select v-model="search.role_id" @change="getUsers(true)">
            <el-option label="请选择" :value="-1"> </el-option>
            <el-option label="无角色" :value="0"> </el-option>
            <el-option
              v-for="role in roleList"
              :key="role.role_id"
              :label="role.role_name"
              :value="role.role_id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="float:right">
          <el-button type="success" icon="el-icon-plus" @click="beginAdd"
            >添加</el-button
          >
        </el-form-item>
      </el-form>
    </el-header>
    <el-main>
      <el-table
        ref="singleTable"
        :data="list"
        highlight-current-row
        border
        stripe
      >
        <el-table-column type="index" width="50" align="center" label="#">
        </el-table-column>
        <el-table-column property="user_name" label="用户名" width="150">
        </el-table-column>
        <el-table-column
          property="user_pwd"
          label="密码"
          width="120"
          align="center"
        >
          <template slot-scope="{ row }">
            <el-popover trigger="hover" placement="right">
              <p>
                密码：<span>
                  {{ row.user_pwd }}
                </span>
              </p>

              <el-button type="text" icon="el-icon-view" slot="reference"
                >查看</el-button
              >
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="角色名" width="180" align="center">
          <template slot-scope="{ row }">
            <span
              v-if="row.role_id"
              v-text="
                roleList.find((item) => item.role_id === row.role_id).role_name
              "
            >
            </span>
            <span v-else style="color:#aaa">
              无角色
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{ row }">
            <el-popover
              placement="right"
              width="400"
              trigger="click"
              style="margin-right:15px"
            >
              <el-form ref="form" label-width="80px" inline>
                <el-form-item label="角色分配">
                  <el-select v-model="role_id" placeholder="请选择角色">
                    <el-option label="请选择" :value="-1"> </el-option>
                    <el-option label="无角色" :value="0"></el-option>
                    <el-option
                      v-for="item in roleList"
                      :key="item.role_id"
                      :label="item.role_name"
                      :value="item.role_id"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button
                    type="primary"
                    @click="configUserRole(row.user_name)"
                    >分配</el-button
                  >
                </el-form-item>
              </el-form>
              <el-button
                type="warning"
                plain
                icon="el-icon-edit"
                slot="reference"
                @click="role_id = row.role_id || 0"
                >分配角色</el-button
              >
            </el-popover>

            <el-button
              type="primary"
              plain
              icon="el-icon-share"
              @click="beginUpdate(row)"
              >修改</el-button
            >
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              @click="remove(row.user_name)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <el-footer height="32px">
      <el-pagination
        hide-on-single-page
        background
        layout="prev, pager, next,jumper,->,sizes,total"
        :total="pagination.total"
        :page-sizes="[5, 8, 10, 12, 15]"
        :page-size.sync="pagination.pageSize"
        :current-page.sync="pagination.currentPage"
        @current-change="getUsers(false)"
        @size-change="getUsers(true)"
      >
      </el-pagination>
    </el-footer>
    <!-- 弹出对话框 -->
    <el-dialog :visible.sync="editor.isEditor" width="40%" :modal="false">
      <p slot="title">
        {{ editor.isMode ? "新增用户" : `编辑用户-${editor.mode.user_name}` }}
      </p>
      <el-form
        ref="ruleForm"
        :model="editor.mode"
        label-width="80px"
        :rules="editor.rules"
      >
        <el-form-item label="用户名" prop="user_name" v-if="editor.isMode">
          <el-input v-model="editor.mode.user_name"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="user_pwd">
          <el-input v-model="editor.mode.user_pwd"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="saveInfo">保存</el-button>
        <el-button @click="editor.isEditor = false">取消</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import { createNamespacedHelpers } from "vuex";
import { UserApi } from "@/util/api.js";
const { mapState, mapActions } = createNamespacedHelpers("role");
export default {
  name: "User",
  data() {
    return {
      search: {
        user_name: "",
        role_id: -1,
      },
      pagination: {
        total: 0,
        pageSize: 5,
        currentPage: 1,
      },
      list: [],
      role_id: -1,
      timerValid: null,
      editor: {
        isEditor: false,
        isMode: true,
        mode: {
          user_name: "",
          user_pwd: "",
        },
        rules: {
          user_name: [
            {
              validator: (rule, value, callback) => {
                // 防抖 执行
                if (this.timerValid) clearTimeout(this.timerValid);
                this.timerValid = setTimeout(async () => {
                  if (value === "") callback(new Error("用户名不能为空"));
                  else if (value.length < 3 || value.length > 10)
                    callback(new Error("用户名要在3-9的字符之内"));
                  else {
                    let count = await UserApi.validName(value);
                    if (count > 0) callback(new Error("用户名已经存在"));
                    else callback();
                  }
                }, 400);
              },
              trigger: "change",
            },
          ],
          user_pwd: [
            { required: true, message: "请输入密码", trigger: "blur" },
            {
              min: 3,
              max: 6,
              message: "长度在 3 到 6 个字符",
              trigger: "blur",
            },
          ],
        },
      },
    };
  },
  async created() {
    await this.roleInit();
    this.getUsers(true);
  },
  methods: {
    initForm() {
      // 起初是不显示的 所以判断一下 或者等它渲染完 在执行 不然第一次找不到
      if (this.$refs.ruleForm) this.$refs.ruleForm.resetFields();
    },
    beginAdd() {
      // 开始新增
      // 对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
      this.initForm();
      this.editor.mode.user_name = "";
      this.editor.mode.user_pwd = "";
      this.editor.isEditor = true;
      this.editor.isMode = true;
    },
    beginUpdate(row) {
      // 开始修改
      // 对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
      this.initForm();
      this.editor.mode.user_name = row.user_name;
      this.editor.mode.user_pwd = row.user_pwd;
      this.editor.isEditor = true;
      this.editor.isMode = false;
    },
    saveInfo() {
      // 保存修改or新增
      this.$refs.ruleForm
        .validate()
        .then(async (res) => {
          // 验证成功
          if (this.editor.isMode) {
            // 新增
            await UserApi.add(this.editor.mode);
            // 新增到数据库 默认role_id为null
            this.list.push({ ...this.editor.mode, role_id: null });
            this.$message({
              type: "success",
              message: "新增成功",
            });
          } else {
            // 修改
            await UserApi.update(this.editor.mode);
            this.list[
              this.list.findIndex(
                (item) => item.user_name === this.editor.mode.user_name
              )
            ].user_pwd = this.editor.mode.user_pwd;
            this.$message({
              type: "success",
              message: "修改成功",
            });
          }
          this.editor.isEditor = false;
        })
        .catch((err) => {
          // 验证失败
        });
    },
    ...mapActions({ roleInit: "init" }),
    async getUsers(isInit = true) {
      if (isInit) {
        this.pagination.currentPage = 1;
      }

      const { total, list } = await UserApi.list({
        ...this.search,
        begin: (this.pagination.currentPage - 1) * this.pagination.pageSize,
        pageSize: this.pagination.pageSize,
      });
      this.list = list;
      this.pagination.total = total;
    },
    async configUserRole(user_name) {
      await UserApi.configRole({
        user_name: user_name,
        role_id: this.role_id,
      });
      let target = this.list.find((item) => item.user_name === user_name);
      target.role_id = this.role_id || null;
      this.$message({
        message: `用户${user_name}角色设置成功`,
        type: "success",
      });
    },
    remove(user_name) {
      this.$confirm(`确定要删除用户:${user_name}`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // await this.$http({
          //   method: "post",
          //   url: `/user/remove/${user_name}`,
          // });
          await UserApi.remove(user_name);

          this.list.splice(
            this.list.findIndex((item) => item.user_name === user_name),
            1
          );
          this.pagination.total = this.pagination.total - 1;
          this.$message({
            message: `系统用户:"${user_name}",删除成功`,
            type: "success",
          });
          this.$nextTick(() => {
            if (this.list.length === 0) this.getUsers(false);
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  computed: {
    ...mapState({ roleList: "list" }),
  },
};
</script>

<style lang="stylus" scoped>
.el-container
  position absolute
  left 0
  top 0
  righ 0
  bottom 0
    .el-header
      overflow hidden
</style>
